package com.example.demo.controller;

import com.example.demo.service.UserService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.example.demo.model.User;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@lombok.Data
public class UserController {

    private final List<User> users = new ArrayList<>();

    @Autowired
    private UserService userService;

    @Autowired
    public UserController() {
        // code to initialize users from database
        System.out.println("Initializing users");
        User user = new User(111L,"John", "john@example.com");
        System.out.println(user);
        users.add(user);
        System.out.println(users);

        users.add(new User(222L, "Jane", "jane@example.com"));
        users.add(new User(333L, "Bob", "bob@example.com"));

        System.out.println(users);
    }

    @PostConstruct
    public void init() {
        System.out.println("Initializing users");
        users.add(new User(111L,"John", "john@example.com"));
        users.add(new User(222L, "Jane", "jane@example.com"));
        users.add(new User(333L, "Bob", "bob@example.com"));

        System.out.println(users);
    }

    @GetMapping("/{name}")
    public User getUsers(@PathVariable("name") String name) {
        String msg = "This is a list of users" + name;
        System.out.println(msg);

        for (User user : users) {
            System.out.println(user);

            if (user.getName().equals(name)) {
                return user;
            }
        }
        return null;
    }

    @GetMapping("/add-show")
    public User addAndGetUser() {
        User user = new User(444L, "Alice", "alice@example.com");
        users.add(user);
        return user;
    }

    @PostMapping("/new")
    public User addUser(@RequestBody User user) {
        // code to add user to database
        System.out.println("Adding user");
        System.out.println(user);
        user.setId((long) users.size() + 1);
        users.add(user);
        return user;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable("id") Long id) {
        for (User user : users) {
            if (user.getId().equals(id)) {
                return user;


            }
        }
        return null;

    }

    @GetMapping("/all")
    public List<User> getAllUsers() {
        // code to get all users from database
        System.out.println("Getting all users");
        System.out.println(users);
        return users;
    }

    @GetMapping("/show")
    public void show() {
        System.out.println("Showing all users");

    }


    @GetMapping("/perform-action")
    public String performSomeAction() {
        userService.performSomeAction();
        return "Action performed successfully";
    }
}